//
//  WXAuth2ViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/14.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "WXAuth2ViewController.h"
#import "LoginViewController.h"
#import "MainViewController.h"
#import "RegisterInfoViewController.h"

//Tools
#import "WXApi.h"
#import "WXApiManager.h"
#import "AppUtil.h"

//Request
#import "HTTPPromise+Login.h"

//Model
#import "WXAuth2Model.h"
#import "UserInfoModel.h"

@interface WXAuth2ViewController ()<WXApiManagerDelegate>
{
    NSDictionary *userToken;
    
}
@property (nonatomic,strong) WXAuth2Model *auth2Model;
@property (nonatomic,strong) UserInfoModel *userInfoModel;

- (IBAction)loginWX:(id)sender;
@end

@implementation WXAuth2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [WXApiManager sharedManager].delegate = self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)loginWX:(id)sender {
    //判断微信已安装是否安装。
    BOOL isWX = [WXApi isWXAppInstalled];
    NSLog(@"-------------%d",isWX);
    if(isWX){
        SendAuthReq* req = [[SendAuthReq alloc ] init];
        req.openID = WXKey;
        req.scope = kAuthScope;
        req.state = false;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendAuthReq:req viewController:self delegate:[WXApiManager sharedManager]];
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示"message:@"当前微信版本过低，请先升级" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:actionConfirm];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - private
- (void)requestWeiXin{
    NSDictionary *doctorParam = @{@"authorizationCode":authorizationCode,@"deviceId":IDFV};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:doctorParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:doctorParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestWeiXinCreateParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        //(数据转模型)
        int successRet =[responseObj[@"ret"] intValue];
        NSLog(@"%d",successRet);
        if (successRet == 0) {
            strongSelf.auth2Model = [[WXAuth2Model alloc] init];
            [strongSelf.auth2Model setValuesForKeysWithDictionary:responseObj[@"userToken"]];
            [strongSelf assembleKey];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
         NSLog(@"%@",error.userInfo);
    }];
}

- (void)requestUser{
    NSDictionary *doctorParam = @{};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:doctorParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:doctorParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestUserInfoParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            strongSelf.userInfoModel = [[UserInfoModel alloc] init];
            [strongSelf.userInfoModel setValuesForKeysWithDictionary:responseObj[@"info"]];
            NSLog(@"signKey :%@",strongSelf.userInfoModel.mobile);
            HTCFUDFCache(kMobileKey,strongSelf.userInfoModel.mobile);
            HTCFUDFCache(kNickNameKey,strongSelf.userInfoModel.nickname);
            HTCFUDFCache(kPortraitKey, strongSelf.userInfoModel.portrait);
            
            
            HTCFUDFCache(kRoleKey, [NSNumber numberWithInt:strongSelf.userInfoModel.role]);
            roleType = [HTCFUDFGetValue(kRoleKey) intValue];
            
            NSLog(@"roleType-----------------------%d",roleType);
            [strongSelf skipController];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}


/**
    组装密钥
 */
- (void)assembleKey{
    NSLog(@"%@",_auth2Model.accessToken);
    HTCFUDFCache(kAccessTokenKey,_auth2Model.accessToken);
    accessToken = HTCFUDFGetValue(kAccessTokenKey);
    
    NSString *encryptionStr = [NSString stringWithFormat:@"%@|%@|%@|%@",_auth2Model.accessToken,_auth2Model.userId,_auth2Model.reflashToken,IDFV];
    NSLog(@"encryptionStr :%@",encryptionStr);
    
    HTCFUDFCache(kRefreshTokenKey,_auth2Model.reflashToken);
    refreshToken = _auth2Model.reflashToken;
    
    HTCFUDFCache(kUserIdKey,_auth2Model.userId);
    userId = [HTCFUDFGetValue(kUserIdKey) intValue];
    NSLog(@"%d",userId);
    
    HTCFUDFCache(kSignKey,_auth2Model.signKey);
    signKey = HTCFUDFGetValue(kSignKey);
    
    NSLog(@"signKey :%@",_auth2Model.signKey);
    NSString *privateKey = HTCFAES128EncryptUtil(encryptionStr,signKey);
    NSLog(@"%@",privateKey);
    HTCFUDFCache(kSignServiceKey,privateKey);
    encryptionToken = privateKey;
    
    //请求接口
    [self requestUser];
}

- (void)skipController{
    if(HTCFStringIsNull(_userInfoModel.mobile))
    {
        HTCFUDFCache(kNickNameKey,_userInfoModel.nickname);
        nickname = HTCFUDFGetValue(kNickNameKey);
        
        LoginViewController *loginVC = [[LoginViewController alloc] init:_userInfoModel.role];
        if(self.presentingViewController)
        {
            [self presentViewController:loginVC animated:YES completion:nil];
        }else{
            [self.navigationController pushViewController:loginVC animated:YES];
        }

    }else if (roleType == -1)
    {
        RegisterInfoViewController *registerInfoVC = [[RegisterInfoViewController alloc] init];
        if(self.presentingViewController)
        {
            [self presentViewController:registerInfoVC animated:YES completion:nil];
        }else{
            [self.navigationController pushViewController:registerInfoVC animated:YES];
        }
    }else{
        if(self.presentingViewController)
        {
            UIViewController *vc =  self;
            while (vc.presentingViewController) {
                vc = vc.presentingViewController;
            }
            NSLog(@"vc:========%@",vc);
            [vc dismissViewControllerAnimated:YES completion:nil];
        }else{
            MainViewController *mainVC = [[MainViewController alloc] init];
            self.navigationController.navigationBarHidden = YES;
            [self.navigationController pushViewController:mainVC animated:YES];
        }
    }
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", response.code, response.state, response.errCode];
    NSLog(@"%@",strMsg);
    switch (response.errCode) {
        case WXSuccess:{
            //成功
            if(!HTCFStringIsNull(response.code)){
                authorizationCode = response.code;
                HTCFUDFCache(kAuthorizationKey,response.code);
                
                [self requestWeiXin];
            }
        }
            break;
        case WXErrCodeCommon:
            break;
        case WXErrCodeUserCancel:
            break;
        case WXErrCodeSentFail:
            break;
        case WXErrCodeAuthDeny:
            break;
        case WXErrCodeUnsupport:
            break;
    }
}
@end
